package com.sky.service.impl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override//营业额统计接口
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endTime);
           Double turnover= orderMapper.sumBymap(map);
           turnover=turnover==null? 0.0 : turnover;
           turnoverList.add(turnover);
        }
        TurnoverReportVO turnoverReportVO= TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
        return turnoverReportVO;

    }

    @Override// 用户统计
    public UserReportVO getuser(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            Integer newUsers=userMapper.getUserCount(map);
            newUserList.add(newUsers);
            map.put("end",endTime);
            Integer totalUser=userMapper.getUserCount(map);
            totalUserList.add(totalUser);
        }
        UserReportVO userReportVO=UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
        return userReportVO;
    }

    @Override//订单统计
    public OrderReportVO getOrders(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer>orderCountList=new ArrayList<>();//总订单数
        List<Integer>validOrderCountList=new ArrayList<>();//有效订单数
        Integer totalOrderCount=0;
        Integer vaildOrderCount=0;

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("status",Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end",endDateTime);
            Integer OrdersCount=orderMapper.CountByMap(map);
            orderCountList.add(OrdersCount);
            totalOrderCount+=OrdersCount;//时间区间内的总订单数
            Integer validCount=orderMapper.CountByMap(map);
            validOrderCountList.add(validCount);
            vaildOrderCount+=validCount;//时间区间内的总有效订单数
        }
        //订单完成率
        Double orderCompletionRate=0.0;
        if (totalOrderCount!=0){
            orderCompletionRate=vaildOrderCount.doubleValue()/totalOrderCount;
        }
        OrderReportVO orderReportVO=OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(vaildOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return orderReportVO;
    }

    @Override//销量排名Top10
    public SalesTop10ReportVO gettop(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO>goodsSalesDTOList=orderMapper.getSalesTop10();
        List<String> nameList=goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList=goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        SalesTop10ReportVO salesTop10ReportVO=SalesTop10ReportVO
                .builder()
                .numberList(StringUtils.join(numberList,","))
                .nameList(StringUtils.join(nameList,","))
                .build();
        return salesTop10ReportVO;
    }

    @Override//导出运营数据Excel报表
    public void excel(HttpServletResponse response) throws IOException {
        LocalDate now = LocalDate.now();//获得今天的日期
        LocalDate begin = now.minusDays(30);//开始日期
        LocalDate end = now.minusDays(1);//结束日期
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        //查询最近30天的运营数据
        BusinessDataVO businessData = workspaceService.getData(beginTime,endTime);
        //使用一个输入流读取到指定的模板文件，动态获取文件的位置
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //将查询到的数据写到Excel表格中
        XSSFWorkbook excel = new XSSFWorkbook(in);
        //读取到第一个Sheet页
        XSSFSheet sheet = excel.getSheet("Sheet1");
        //找到第2行，第2个单元格
        sheet.getRow(1).getCell(1).setCellValue(begin.toString()+"至"+end.toString());
        //营业额
        sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        //订单完成率
        sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        //新增用户数
        sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        //有效订单
        sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        //平均客单价
        sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //准备明细数据
           businessData = workspaceService.getData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(3).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessData.getUnitPrice());
            row.getCell(6).setCellValue(businessData.getNewUsers());
        }
        //通过输出流将文件下载到客户端浏览器中
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);
        //关闭资源
        out.flush();

    }


}

